package com.zatech.cgnci.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.base.utils.ConvertUtils;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.entity.CgnciReinsuranceInfoDO;
import com.zatech.cgnci.project.entity.CgnciReinsuranceRiskDO;
import com.zatech.cgnci.project.entity.CgnciReinsurerDO;
import com.zatech.cgnci.project.entity.CgnciUnderwritingPolicyDO;
import com.zatech.cgnci.project.mapper.CgnciUnderwritingPolicyMapper;
import com.zatech.cgnci.project.service.*;
import com.zatech.cgnci.project.vo.CgnciUnderwritingPolicyVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 承保政策表 服务实现类
 * </p>
 *
 * @author Generator
 * @since 2024-12-17
 */
@Service
public class CgnciUnderwritingPolicyServiceImpl extends ServiceImpl<CgnciUnderwritingPolicyMapper, CgnciUnderwritingPolicyDO> implements CgnciUnderwritingPolicyService {

    @Resource
    CgnciReinsuranceInfoService reinsuranceInfoService;
    @Resource
    CgnciReinsuranceRiskService reinsuranceRiskService;
    @Resource
    CgnciReinsurerService reinsurerService;
    @Resource
    CgnciReinsuranceRiskLayerService reinsuranceRiskLayerService;

    @Override
    public void deleteUnderwritingPolicy(Long policyId, String reinsuranceArrangement) {
        CgnciUnderwritingPolicyDO policyDO = this.getById(policyId);
        if (VerifyUtils.isEmpty(policyDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "policyId有误");
        }
        if (VerifyUtils.isEmpty(policyDO.getRiskSubTypeCode())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, policyId + ":超净自留riskSubTypeCode为空");
        }

        // 获取当前再保分出安排
        String sourceArrangement = policyDO.getReinsuranceArrangement();
        // 返回过滤掉的再保分出安排
        String filterArrangement = filterNumbers(sourceArrangement, reinsuranceArrangement);
        if (VerifyUtils.isEmpty(filterArrangement)) {
            return;
        }
        // 如果过滤的再保分出安排包含临分分出,则删除临分分出对应的险种
        if (filterArrangement.contains("1")) {
            // 查询临分分出信息
            CgnciReinsuranceInfoDO divideOutReinsuranceInfoDO = reinsuranceInfoService.getOne(new LambdaQueryWrapper<CgnciReinsuranceInfoDO>()
                    .eq(CgnciReinsuranceInfoDO::getBusinessId, policyDO.getBusinessId())
                    .eq(CgnciReinsuranceInfoDO::getReinsuranceType, "3"));
            if (VerifyUtils.isNotEmpty(divideOutReinsuranceInfoDO)) {
                // 查询分出--险种信息
                CgnciReinsuranceRiskDO divideOutReinsuranceRiskDO = reinsuranceRiskService.getOne(new LambdaQueryWrapper<CgnciReinsuranceRiskDO>()
                        .in(CgnciReinsuranceRiskDO::getReinsuranceId, divideOutReinsuranceInfoDO.getReinsuranceId())
                        .eq(CgnciReinsuranceRiskDO::getRiskSubTypeCode, policyDO.getRiskSubTypeCode()));
                if (VerifyUtils.isNotEmpty(divideOutReinsuranceRiskDO)) {
                    // 处理分出信息汇总字段
                   // reinsuranceInfoService.updateReinsuranceColumn(divideOutReinsuranceRiskDO, divideOutReinsuranceInfoDO, null);

                    // 删除分出--险种信息
                    reinsuranceRiskService.removeById(divideOutReinsuranceRiskDO.getReinsuranceRiskId());
                }

                // 查询分出--再保人
                List<CgnciReinsurerDO> divideOutReinsurerList = reinsurerService.list(new LambdaQueryWrapper<CgnciReinsurerDO>()
                        .in(CgnciReinsurerDO::getReinsuranceId, divideOutReinsuranceInfoDO.getReinsuranceId()));
                if (VerifyUtils.isNotEmpty(divideOutReinsurerList)) {
                    divideOutReinsurerList.forEach(divideOutReinsurer -> {
                        // 查询分出--再保人--险种信息
                        CgnciReinsuranceRiskDO divideOutReinsurerRiskDO = reinsuranceRiskService.getOne(new LambdaQueryWrapper<CgnciReinsuranceRiskDO>()
                                .in(CgnciReinsuranceRiskDO::getReinsuranceId, divideOutReinsurer.getReinsurerId())
                                .eq(CgnciReinsuranceRiskDO::getRiskSubTypeCode, policyDO.getRiskSubTypeCode()));
                        if (VerifyUtils.isNotEmpty(divideOutReinsurerRiskDO)) {
                            // 处理分出--再保人汇总字段
                          //  reinsurerService.updateReinsurerColumn(divideOutReinsurerRiskDO, divideOutReinsurer, null);

                            // 删除分出--再保人险种
                            reinsuranceRiskService.removeById(divideOutReinsurerRiskDO.getReinsuranceRiskId());
                        }
                    });
                }
            }
        }

        // 如果过滤的再保分出安排包含合约分出,则删除整个合约分出信息
        if (filterArrangement.contains("2")) {
            // 查询合约分出信息
            List<CgnciReinsuranceInfoDO> list = reinsuranceInfoService.list(new LambdaQueryWrapper<CgnciReinsuranceInfoDO>()
                    .eq(CgnciReinsuranceInfoDO::getBusinessId, policyDO.getBusinessId())
                    .eq(CgnciReinsuranceInfoDO::getReinsuranceType, "2"));
            if (VerifyUtils.isNotEmpty(list)) {
                reinsuranceInfoService.removeByIds(list.stream().map(CgnciReinsuranceInfoDO::getReinsuranceId).collect(Collectors.toSet()));
            }
        }

        // 更新再保分出安排
        policyDO.setReinsuranceArrangement(reinsuranceArrangement);
        this.updateById(policyDO);
    }

    @Override
    public void deletePolicy(Long id) {
        // 删除超净自留
        List<CgnciUnderwritingPolicyDO> policyList = this.list(new LambdaQueryWrapper<CgnciUnderwritingPolicyDO>().eq(CgnciUnderwritingPolicyDO::getBusinessId, id));
        if (VerifyUtils.isNotEmpty(policyList)) {
            this.removeByIds(policyList.stream().map(CgnciUnderwritingPolicyDO::getPolicyId).collect(Collectors.toSet()));
        }
        // 删除分出
        List<CgnciReinsuranceInfoDO> reinsuranceList = reinsuranceInfoService.list(new LambdaQueryWrapper<CgnciReinsuranceInfoDO>()
                .eq(CgnciReinsuranceInfoDO::getBusinessId, id)
                .in(CgnciReinsuranceInfoDO::getReinsuranceType, Arrays.asList(2, 3)));
        if (VerifyUtils.isNotEmpty(reinsuranceList)) {
            reinsuranceInfoService.removeByIds(reinsuranceList.stream().map(CgnciReinsuranceInfoDO::getReinsuranceId).collect(Collectors.toSet()));
        }
    }

    @Override
    public List<CgnciUnderwritingPolicyVO> listUnderwritingPolicyByBusinessId(Long businessId) {
        List<CgnciUnderwritingPolicyDO> underwritingPolicyDOList = this.list(new LambdaQueryWrapper<CgnciUnderwritingPolicyDO>()
                .eq(CgnciUnderwritingPolicyDO::getBusinessId, businessId));
        return ConvertUtils.convert(underwritingPolicyDOList, CgnciUnderwritingPolicyVO.class);
    }

    @Override
    public void deleteUnderwritingPolicyRisk(Long businessId, String riskSubTypeCode) {
        // 查询超净自留处理方式
        CgnciUnderwritingPolicyDO policyDO = this.getOne(new LambdaQueryWrapper<CgnciUnderwritingPolicyDO>()
                .eq(CgnciUnderwritingPolicyDO::getBusinessId, businessId)
                .eq(CgnciUnderwritingPolicyDO::getRiskSubTypeCode, riskSubTypeCode)
        );
        if (VerifyUtils.isNotEmpty(policyDO)) {
            this.removeById(policyDO.getPolicyId());
        }
    }

    /**
     * 返回过滤掉的再保分出安排
     */
    private String filterNumbers(String numbers, String numbersToFilter) {
        if (VerifyUtils.isEmpty(numbersToFilter)) {
            return numbers;
        }
        // 按逗号分隔字符串
        String[] numberArray = numbers.split(",");

        // 使用 StringBuilder 来构建新的字符串
        StringBuilder sb = new StringBuilder();

        // 遍历数组，过滤掉不需要的数字
        for (String number : numberArray) {
            boolean shouldFilter = false;
            for (String filterNumber : numbersToFilter.split(",")) {
                if (number.equals(filterNumber)) {
                    shouldFilter = true;
                    break;
                }
            }
            if (!shouldFilter) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(number);
            }
        }
        // 返回过滤后的字符串
        return sb.toString();
    }

}
